package com.school.manager.handle;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.school.manager.common.Constants;
import com.school.manager.entity.po.SysUserPo;


@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler{
	
	@Autowired
	private HttpServletRequest request;

	/**
	 * 设置新增数据时自动填充字段
	 */
	@Override
	public void insertFill(MetaObject metaObject) {
		SysUserPo currentUser = (SysUserPo) request.getSession().getAttribute(Constants.CURRENT_USER);
		this.setFieldValByName("createTime", System.currentTimeMillis(), metaObject);
		this.setFieldValByName("updateTime", System.currentTimeMillis(), metaObject);
		if (currentUser == null) {
			this.setFieldValByName("createUser", "superadmin", metaObject);
			this.setFieldValByName("updateUser", "superadmin", metaObject);
			return;
		}
		this.setFieldValByName("createUser", currentUser.getId(), metaObject);
		this.setFieldValByName("updateUser", currentUser.getId(), metaObject);
	}

	/**
	 * 设置修改数据时自动填充字段
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		SysUserPo currentUser = (SysUserPo) request.getSession().getAttribute(Constants.CURRENT_USER);
		this.setFieldValByName("updateTime", System.currentTimeMillis(), metaObject);
		this.setFieldValByName("updateUser", currentUser.getId(), metaObject);
	}

}
